function get_appropriate_ws_url(extra_url)
{
	var pcol;
	var u = document.URL;

	/*
	 * We open the websocket encrypted if this page came on an
	 * https:// url itself, otherwise unencrypted
	 */

	if (u.substring(0, 5) === "https") {
		pcol = "wss://";
		u = u.substr(8);
	} else {
		pcol = "ws://";
		if (u.substring(0, 4) === "http")
			u = u.substr(7);
	}

	u = u.split("/");

	/* + "/xxx" bit is for IE10 workaround */

	return pcol + u[0] + "/" + extra_url;
}

function new_ws(urlpath, protocol)
{
	if (typeof MozWebSocket != "undefined")
		return new MozWebSocket(urlpath, protocol);

	return new WebSocket(urlpath, protocol);
}

function KV(key, value){
	var kvJSON="";
	kvJSON = "\""+key+"\""+":"+"\""+value+"\"";
	return kvJSON;
}

function KJ(key, sJson){
	var kvJSON="";
	kvJSON = "\""+key+"\""+":"+sJson;
	return kvJSON;
}

document.addEventListener("DOMContentLoaded", function() {
	
	ws = new_ws(get_appropriate_ws_url(""), "dumb-increment-protocol");
	try {
		ws.onopen = function() {
			//document.getElementById("m").disabled = 0;
			//document.getElementById("b").disabled = 0;
		};
	
		ws.onmessage =function got_packet(msg) {
			//alert(msg.data);
			var dataObject = JSON.parse(msg.data);
			var hotElement = document.querySelector('#hot');
			newHandsontable(hotElement, dataObject);
		};
	
		ws.onclose = function(){
			/*
			document.getElementById("m").disabled = 1;
			document.getElementById("b").disabled = 1;
			*/
		};
	} catch(exception) {
		alert("<p>Error " + exception);  
	}
	
	function sendmsg()
	{
  		var ctxArray = new Array()
		ctxArray[0] = document.getElementById("txtbox_Name").value;
		ctxArray[1] = document.getElementById("txtbox_Value").value;
		ctxArray[2] = document.getElementById("txtbox_Quantity").value;
		ctxArray[3] = document.getElementById("txtbox_Factory").value;
		var DATA = "{"+
				  	KV("Name", ctxArray[0])+","+
				  	KV("Value", ctxArray[1])+","+
				  	KV("Quantity", ctxArray[2])+","+
				  	KV("Factory", ctxArray[3])+
			  	  "}";
		var ctxJSON = "{"+
						KV("Action", "insert into table")+","+
						KJ("Data", DATA)+
					  "}";
		//alert(ctxJSON);
		ws.send(ctxJSON);
	}

	function getdata()
	{
		var ctxJSON = "{"+
						KV("Action", "select * from table")+","+
						KV("Data", "")+
					  "}";
		ws.send(ctxJSON);
	}

	document.getElementById("btn_write").addEventListener("click", sendmsg);
	document.getElementById("btn_read").addEventListener("click", getdata);

}, false);
